package com.market.controller.admin;


import com.market.annotation.AdminLogAnnotation;
import com.market.bean.*;
import com.market.bean.common.BaseRespVo;
import com.market.bean.common.BaseStatVo;
import com.market.config.realm.MarketToken;
import com.market.service.admin.AdminAuthService;
import com.market.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AdminAuthController {

    @Autowired
    AdminAuthService authService;

    /**
     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @AdminLogAnnotation
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map, HttpServletRequest request) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken authenticationToken = new MarketToken(username, password, "admin");
        try {
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return BaseRespVo.error();
        }
        //判断是否认证成功   失败后重定向

        boolean authenticated = subject.isAuthenticated();
        // 可以获得session信息，也可以获得其sessionId
        Session session = subject.getSession();

        String ip = request.getRemoteHost() + ":" + request.getRemotePort();
        session.setAttribute("username", username);
        session.setAttribute("ip", ip);

        // 获得Principal信息 → realm的doGetAuthorizationInfo方法构造的认证信息里的第一个参数
        MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();

        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        // adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setAvatar(marketAdmin.getAvatar());
        // adminInfo.setNickName("admin123");
        adminInfo.setNickName(marketAdmin.getUsername());
        loginUserData.setAdminInfo(adminInfo);
        // loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        loginUserData.setToken((String) session.getId());
        return BaseRespVo.ok(loginUserData);
    }


    @RequestMapping("info")
    public BaseRespVo info(String token) {

/*
        //开发完shiro之后，再整合
        InfoData infoData = new InfoData();
        infoData.setName("admin123");

        //根据primaryPrincipal做查询
        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        ArrayList<String> roles = new ArrayList<>();
        roles.add("超级管理员");
        infoData.setRoles(roles);
        ArrayList<String> perms = new ArrayList<>();
        perms.add("*");
        infoData.setPerms(perms);


        return BaseRespVo.ok(infoData);*/
        if (StringUtil.isEmpty(token)) {
            return BaseRespVo.invalidParameter("参数不合法");
        }
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.unAuthc();
        }
        MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
        InfoData data= authService.info(marketAdmin);
        return BaseRespVo.ok(data);
    }

    @AdminLogAnnotation
    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

}
